package com.collectplus.express;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.DrawerLayout;
import android.view.KeyEvent;
import android.widget.LinearLayout;

import com.baidu.location.BDLocation;
import com.collectplus.express.home.HomeFragment;
import com.collectplus.express.logic.AppCache;
import com.collectplus.express.logic.AppConfig;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.JSON;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.menu.MenuFragment;
import com.collectplus.express.model.AppConfigBean;
import com.collectplus.express.model.BannerBean;
import com.collectplus.express.model.CheckUpdateModel;
import com.collectplus.express.model.Const;
import com.collectplus.express.model.OrderBean;
import com.collectplus.express.tools.SharedPref;
import com.collectplus.express.upgrade.UpgradeActivity;
import com.collectplus.express.wxapi.Constants;
import com.shouhuobao.bhi.loc.BaiduLocationService;
import com.shouhuobao.bhi.login.GuildActivity;
import com.tencent.android.tpush.XGPushManager;

import java.util.ArrayList;
import java.util.List;

import droid.frame.activity.ActivityMgr;
import droid.frame.fragment.FragmentMgr;
import droid.frame.fragment.FrameBaseFragment;
import droid.frame.push.PushInterface;
import droid.frame.utils.android.Alert;
import droid.frame.utils.android.Log;

/**
 * 程序主界面
 *
 * @author coffee<br>
 * 2015-12-28上午10:26:55
 */
public class MainActivity extends BaseActivity2 {

    private static MainActivity instance;

    private DrawerLayout mDrawerLayout;
    private LinearLayout mDrawerLeft;
    private FrameBaseFragment mContentFragment;
    private MenuFragment mMenuFragment;
    private FragmentMgr fragmentMgr;
    // 判断是否进入后台 (注意onPause、onStop都需要判断, 防止)
    private boolean isFromBackground = true;

    @SuppressLint({"ResourceAsColor", "MissingSuperCall"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 设置状态栏颜色透明
        setStatusBarColor(R.color.transparent);
        super.onCreate(savedInstanceState);
        //崩溃日志上传
        AppHttp.getInstance().crashUpload();
        fragmentMgr = FragmentMgr.getInstance(this);

        setContentView(R.layout.main);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerLeft = (LinearLayout) findViewById(R.id.left_drawer);

        mMenuFragment = new MenuFragment();
        fragmentMgr.replace(mMenuFragment, R.id.left_drawer);
        mContentFragment = new HomeFragment();
        fragmentMgr.replace(mContentFragment, R.id.content_frame);

        if (SharedPref.isFirstOpen(Constants.isLogin)) {
            startActivity(GuildActivity.class);
        }
        // 允许终止TouchEvent
        mDrawerLayout.requestDisallowInterceptTouchEvent(false);
        requestLocation();
        // mDrawerLayout.setDrawerListener(new DrawerListener() {
        //
        // @Override
        // public void onDrawerStateChanged(int state) {
        // }
        //
        // @Override
        // public void onDrawerSlide(View arg0, float f) {
        // }
        //
        // @Override
        // public void onDrawerOpened(View view) {
        // openDrawer();
        // }
        //
        // @Override
        // public void onDrawerClosed(View view) {
        // closeDrawer();
        // }
        // });
    }

    public void requestLocation() {
        Intent intent = new Intent();
        intent.setClass(getContext(), BaiduLocationService.class);
        intent.putExtra("msgId", MsgID.get_main_location);
        startService(intent);
    }

    public void openDrawer() {
        mDrawerLayout.openDrawer(mDrawerLeft);
        mMenuFragment.openDrawer();
    }

    public void closeDrawer() {
        mDrawerLayout.closeDrawer(mDrawerLeft);
    }

    private int backCount;
    private final long DELAY_BACK = 2000;
    private final int MSG_BACK = 1000;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_BACK:
                    backCount = 0;
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (mDrawerLeft.isShown()) {
                    closeDrawer();
                    // 拦截 back键
                    return true;
                } else {
                    if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键
                        for (FrameBaseFragment fragment : fragmentMgr.getAllFragments()) {
                            if (fragment.isToBackStack()) {
                                return super.onKeyDown(keyCode, event);
                            }
                        }
                        // 如果for循环执行完, 所有的FrameBaseFragment均不是toBackStack 则拦截back键盘
                        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() != KeyEvent.ACTION_UP) {
                            backCount++;
                            Log.d("onBackPressed", backCount);
                            if (backCount == 2) {
                                ActivityMgr.finishAll();
                            } else {
                                // Alert.toastByView("再按一次返回键退出", Toast.LENGTH_SHORT).show();
                                Alert.toast("再按一次返回键退出");
                                mHandler.sendEmptyMessageDelayed(MSG_BACK, DELAY_BACK);
                            }
                            return true;
                        }
                    }
                    return super.onKeyDown(keyCode, event);
                }
        }
        return super.onKeyDown(keyCode, event);
    }

    public static MainActivity getInstance() {
        return instance;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        OrderBean order = (OrderBean) intent.getSerializableExtra("order");
        Bundle bundle = intent.getExtras();
        String stationId = "";
        String takeId = "";
        if (bundle != null) {
            stationId = bundle.getString("stationId");
            takeId = bundle.getString("takeId");
        }
        if (isNotEmpty(stationId)) {
            AppHttp.getInstance().getPassportCollectingDetail(stationId, takeId);
        } else {
            // 标准寄件 - 不显示passport
            if (order == null || order.getParcelType() == Const.ParcelType.standard) {
                order = AppCache.getOrder();
                if (order != null) {
                    AppHttp.getInstance().getPassportDetail(order.getParcelId() + "", 0);
                    //                AppLogic.getInstance().showPassportDialog(getContext(), order.getParcelId() + "", null, 0);
                } else {
                    if (bundle != null) {
                        String parcelId = bundle.getString("parcelId");
                        if (isNotEmpty(parcelId)) {
                            AppHttp.getInstance().getPassportDetail(parcelId + "", 0);
                            //                        AppLogic.getInstance().showPassportDialog(getContext(), parcelId, null, 0);
                        }
                    }
                }
            } else {
                AppHttp.getInstance().getPassportDetail(order.getParcelId() + "", 0);
                //            AppLogic.getInstance().showPassportDialog(getContext(), order.getParcelId() + "", null, 0);
            }
        }
        isFromBackground = true;// 刷新passport列表
    }

    /**
     * 如果是
     */
    @Override
    public void onResume() {
        super.onResume();
        instance = this;
        Thread.setDefaultUncaughtExceptionHandler(((ExpressApplication) getApplication()).getUncaughtExceptionHandler());
        /**
         * 从后台进入的
         */
        if (isFromBackground) {
            try {
                // 获取app配置
                AppHttp.getInstance().getAppConfig(this);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (AppCache.getUserId() != 0) {
            PushInterface.init(droid.frame.push.Constants.AppType.HuoJianTouDi);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        // 判断是否进入后台
        isFromBackground = updateState(getContext());
        XGPushManager.onActivityStoped(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 判断是否进入后台
        isFromBackground = updateState(getContext());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (fragmentMgr != null) {
            fragmentMgr.onDestroy(this);
        }
        instance = null;
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case droid.frame.utils.http.MsgID.net_unavailable:
                showToast("当前网络异常, 请稍后重试");
                return true;
            //订单取消回调
            case MsgID.order_cancel:
                AppHttp.getInstance().getAppConfig(getContext());
                return false;
            // 驿站投递包裹--成功
            case MsgID.station_post:
                final AppResult<?> result2 = JSON.parser(msg.obj);
                // 投递成功 -刷新passport
                if (result2.isSuccess()) {
                    AppHttp.getInstance().getAppConfig(getContext());
                }
                return false;
            // 首页获取配置
            case MsgID.get_appConfig:
                final AppResult<AppConfigBean> result = JSON.parser(msg.obj, AppConfigBean.class);
                final AppConfigBean config = result.getResult();
                if (result.isSuccess() || config != null) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (AppConfig.isTest && isNotEmpty(config.getHostUrl())) {
                                //                                    AppConfig.setSERVER_URL_test(config.getHostUrl());
                            }
                            AppCache.setAppConfig(config);
                            CheckUpdateModel item = config.getRelease();
                            // 需要升级
                            if (item != null && item.getIsNeedUpdate() > 0) {
                                if (item.getIsNeedUpdate() == 2 || item.getIsNeedUpdate() == 1) {
                                    Intent intent = new Intent();
                                    intent.setClass(getContext(), UpgradeActivity.class);
                                    intent.putExtra("item", item);
                                    startActivity(intent);
                                }
                            } else {
                                // showToast("当前版本已经是最新版本");
                            }
                            if (mContentFragment instanceof HomeFragment) {
                                HomeFragment home = (HomeFragment) mContentFragment;
                                home.handleNewMsg();
                                home.handlePassport(config.getPassportList());
                                home.handleNotice(config);
                                home.setNeedPayParcels(config.getNeedRepayParcels());
                            }
                        }
                    });
                } else {
                    // 获取配置信息失败
                }
                return false;
            // 获取百度定位
            case MsgID.get_main_location:
                BDLocation loc = (BDLocation) msg.obj;
                if (loc == null) {
                    AppCache.setCurrentCityName("北京市");
                    return false;
                } else {
                    String currentCityName = loc.getCity();
                    if (isNotEmpty(currentCityName)) {
                        if (AppConfig.isOtherCity != 0) {
                            currentCityName = AppConfig.getCityName();
                            AppCache.setCurrentCityName(currentCityName);
                        } else {
                            AppCache.setCurrentCityName(currentCityName);
                        }
//                        AppHttp.getInstance().getHomeNearServicePoint(loc.getLatitude(), loc.getLongitude(), currentCityName);
                    } else {
                        AppCache.setCurrentCityName("北京市");
                    }
                }
                AppHttp.getInstance().getAppBannerData(Const.BannerConfig.TOUDI_ANDROID_APP);
                return false;
            //获取首页banner数据
            case MsgID.get_app_banner_data:
                if (msg.arg1 == Const.BannerConfig.TOUDI_ANDROID_APP) {
                    final AppResult<BannerBean> bannerResult = JSON.parseList(msg.obj, BannerBean.class);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setBannerData((HomeFragment) mContentFragment, bannerResult.getResultList());
                        }
                    });
                }
                return false;
            //获取首页的附近网店数据
//            case MsgID.get_home_nearservicepoint:
//                final AppResult<HomeNearServicePointBean> nearServicePointResult = JSON.parser(msg.obj, HomeNearServicePointBean.class);
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        if (nearServicePointResult.isSuccess()) {
//                            ((HomeFragment) mContentFragment).handleNearServicePoint(nearServicePointResult.getResult());
//                        } else {
//                            ((HomeFragment) mContentFragment).handleNearServicePoint(null);
//                        }
//                    }
//                });
//                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    /**
     * 设置banner数据
     *
     * @param home
     */
    private void setBannerData(HomeFragment home, ArrayList<BannerBean> items) {
        //        try {
        if (null == items || 0 == items.size()) {
            return;
        }
        //            if (config.getBannerDomainList() != null && config.getBannerDomainList().size() > 0) {
        //                ArrayList<BannerBean> items = new ArrayList<BannerBean>();
        //                for (BannerBean bannerBean : config.getBannerDomainList()) {
        //                    if (isEmpty(bannerBean.getCity())) {
        //                        items.add(bannerBean);
        //                    } else {
        //                        if (isNotEmpty(bannerBean.getCity()) && isNotEmpty(AppCache.getCurrentCityName())
        //                                && AppCache.getCurrentCityName().startsWith(bannerBean.getCity())) {
        //                            String date = "2017-11-06";
        //                            String currentDate = DateUtils.getDateFormat().format(new Date());
        //                            //当前时间小于11-06
        //                            if (DateUtils.getDateFormat().parse(date).getTime() > DateUtils.getDateFormat().parse(currentDate).getTime()) {
        //                                if (isTestUser()) {
        //                                    items.add(bannerBean);
        //                                }
        //                            } else {
        //                                items.add(bannerBean);
        //                            }
        //                        }
        //                    }
        //                }
        home.handleBanner(items);
        //            } else {
        //                home.handleBanner(config.getBannerDomainList());
        //            }
        //        } catch (Exception e) {
        //            e.printStackTrace();
        //        }
    }

    /**
     * 判断是否为测试用户
     *
     * @return
     */
    private boolean isTestUser() {
        String[] phoneArrays = new String[]{"13784489528", "18031817101", "15631825800", "13931833842", "15175875355", "15130871684", "13784185376",
                "15832825993", "18732819090", "13785867801", "15333384988", "13833805080", "15354222139", "15210788660"};
        //登录
        if (isLogin()) {
            String userPhone = AppCache.getUser().getPhone();
            boolean fag = false;
            for (String phone : phoneArrays) {
                if (phone.equals(userPhone)) {
                    fag = true;
                    break;
                }
            }
            return fag;
        } else {//未登录
            return false;
        }
    }

    public boolean isFromBackground() {
        return isFromBackground;
    }

    public void setFromBackground(boolean fromBackground) {
        isFromBackground = fromBackground;
    }

    public static boolean updateState(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }
}
